import React, { useState, useEffect, useImperativeHandle, forwardRef } from "react";
import { List, Spin, Button, Modal, message } from "antd";
import { createStyles } from 'antd-style';
import { RedoOutlined } from '@ant-design/icons';
import { getFileList } from '@/services/file/api';


const useStyles = createStyles(({ token }) => {
  return {
    action2: {
      background: "#fff",
      padding: "8px 16px",
      marginBottom: "24px",
    },
    title: {
      marginBottom: "16px"
    }
  };
});


const handleDownload = (file: API.DownloadFile) => {
  const a = document.createElement('a');
  a.href = file.download_url;
  a.download = file.fileName;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

interface ChildComponentHandle {
  refresh: () => void;
}

// 定义子组件的 Props 类型
interface ChildComponentProps { }

const UploadList = forwardRef<ChildComponentHandle, ChildComponentProps>((props, ref) => {
  const { styles } = useStyles();
  const [data, setData] = useState<API.DownloadFile[]>([]); // 定义状态存储列表数据
  const [loading, setLoading] = useState<boolean>(true); // 定义加载状态

  const fetchData = async () => {
    setLoading(true); // 开始加载
    try {
      const response = await getFileList();
      setData(response.data); // 更新数据
    } catch (error) {
      console.error("请求失败：", error);
    } finally {
      setLoading(false); // 加载完成
    }
  };

  useEffect(() => {
    fetchData(); // 组件挂载时调用接口
  }, []); // 空依赖数组，确保只在组件挂载时执行一次

  useImperativeHandle(ref, () => ({
    refresh: () => {
      fetchData()
    },
  }));

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [previewUrl, setPreviewUrl] = useState<string>("");


  const handlePreview = async (file: API.DownloadFile) => {
    try {
      setPreviewUrl(file.preview_url)
      setIsModalOpen(true);
    } catch (error) {
      message.error('文件预览失败');
    }
  };

  const handleClose = () => {
    setIsModalOpen(false);
    setPreviewUrl("")
  };



  return (
    <div className={styles.action2}>
      {loading ? (
        <Spin tip="加载中..." style={{ width: "100%", textAlign: "center", marginTop: 20 }} />
      ) : (
        <List
          header={<div style={{fontWeight:500}}>上传列表  <RedoOutlined onClick={fetchData} style={{ marginLeft: 8 }} /></div>}
          itemLayout="horizontal"
          dataSource={data}
          renderItem={(item: API.DownloadFile) => (
            <List.Item
              actions={[
                <Button color="primary"
                variant="text" onClick={() => handlePreview(item)}>
                  预览
                </Button>,
                <Button

                  color="primary"
                  variant="text"
                  onClick={() => handleDownload(item)}
                  size="small"
                >
                  下载
                </Button>,
              ]}
            >
              {/* 文件名称 */}
              <List.Item.Meta
                title={item.fileName} // 加粗文件名
              />
            </List.Item>
          )}
        />

      )}
      <Modal
        width={800}
        title="文件预览"
        open={isModalOpen}
        onCancel={handleClose}
        footer={null}
      >
        <iframe width={750} style={{minHeight: 400}} src={previewUrl} />
      </Modal>
    </div>
  );
});

export default UploadList;